Categories
JavaScript Tips

Useful JavaScript Tips — Objects, Methods, and URLs

Spread the love

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Select a Method Dynamically

We can select a method dynamically by using the bracket notation.

For example, we can write:

animal[isDog ? 'bark' : 'speak']()

instead of:

if (isDog) {
  animal.bark()
} else {
  animal.speak()
}

They do the same thing.

The first uses the ternary operator.

The second us the if statement.

The first one is shorter, so we can consider using it.

Tools for Debugging

We can use the console object to help us debug.

For instance, we can use console.log to log the value of an expression.

We can write:

console.log(a)

to log the value of a .

Chrome Dev Tools

The output of the console log ends up in the Console tab of the Chrome dev tools.

Debugger

The Chrome Dev Tools window also has a debugger built-in.

We can add breakpoints and check the variable values there.

The debugger is in the Sources tab.

We can go to a file and toggle on breakpoints.

Then the code will pause at the breakpoint.

There is more than one type of breakpoint.

One is the XHR/fetch breakpoint which halts the program when a network request is sent.

DOM breakpoints are triggered when DOM element changes.

Event listener breakpoints are trigger when an event happens.

All variables in the scope are printed when a breakpoint is reached.

We can click the + button on the breakpoint to show the values of the expression.

If we want to continue running the code, we can step over the code to resume execution until the next line and stops.

Step into goes into the function being run.

The same pane has the call stack, which has all the functions called recorded.

We can use:

node --inspect

to debug Node.js apps in the browser.

Call and Apply

call and apply can be used to change the value of this and call a function.

It works with traditional function.

For instance, given the following function:

function greet(greeting) {
  console.log(`${greeting}, ${this.name}`);
}

We can write:

greet.call({
  name: 'james'
}, 'hi');

We used the call function to call greet by setting the value of this with the first argument.

Then pass in the argument we want to the greet function as the second argument.

Therefore, we see that 'hi, james’ is logged in the console.

apply is similar, except the arguments are passed in as an array.

For instance, we can write:

function greet(greeting) {
  console.log(`${greeting}, ${this.name}`);
}

greet.apply({
  name: 'james'
}, ['hi']);

We have an array instead of just the argument as the 2nd argument.

And we get the same result.

Count the Number of Properties in an Object

We can use Object.keys to return an array of noninherited string property keys.

Therefore, we can use the length property to get the number of properties in the object.

For instance, if we have:

const dog = {
  color: 'white',
  breed: 'poodle'
}

Then we can write:

Object.keys(dog).length

Then we get 2 since dog has 2 own properties.

Sort an Array of Object by its Property Value

The sort method can be used to sort an array of objects by its property value.

For instance, if we have:

const list = [
  { color: 'red', size: 'm' },
  { color: 'green', size: 's' },
  { color: 'blue', size: 'xl' }
]

Then we can write:

list.sort((a, b) => (a.color > b.color)

Then we sort the entries by the color property alphabetically.

Then we get that list is:

[
  {
    "color": "blue",
    "size": "xl"
  },
  {
    "color": "green",
    "size": "s"
  },
  {
    "color": "red",
    "size": "m"
  }
]

Encode a URL

JavaScript comes with the encodeURI() function to encode the URL.

For instance, if we have:

encodeURI("http://example.com/ hello!/")

Then we get:

"http://example.com/%20hello!/"

returned.

There’s also the encodeURIComponent() function that encodes everything including the URL path separators.

For instance, we can write:

encodeURIComponent("http://example.com/ hello!/")

Then we get:

"http%3A%2F%2Fexample.com%2F%20hello!%2F"

returned.

Conclusion

We can select a method dynamically with brackets and expressions inside them.

Also, we can encode URLs with encodeURI or encodeURIComponent depending on our needs.

Debugging is also easy with the debugger.

Sorting items is easy if we pass in a callback.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *